import React, { useCallback } from 'react';
import { Head } from 'ice';
import { Button, Card, Dialog, Field, Icon, Input, Pagination, ResponsiveGrid, Table, Tag } from '@alifd/next';
import { useFusionTable, useSetState } from 'ahooks';
import PageHeader from '@/components/PageHeader';
import scheduleService from '@/services/schedule';
import store from '@/store';
import styles from './index.module.scss';
import DialogOperation from './components/DialogOperation';
import LogList from './components/LogList';

const TableActionIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1899388_oxn3zhg34oj.js',
});

const Schedule = () => {
  const [state, setState] = useSetState({
    optCol: null,
    actionType: 'preview',
    actionVisible: false,
    loading: false,
    isZebra: false,
    size: 'medium',
    multipleBatchBtnDis: true,
    selected: [],
    logVisible: false,
  });
  const { actionVisible, optCol } = state;
  const scheduleDispatchers = store.useModelDispatchers('schedule');
  const field = Field.useField([]);
  const { tableProps, paginationProps, search } = useFusionTable(scheduleService.list, {
    defaultPageSize: 15,
    field,
    cacheKey: 'tableProps',
    formatResult: (response) => {
      return {
        list: response.page.list,
        total: response.page.totalCount,
      };
    },
  });

  const { reset } = search;

  const operationCallback = useCallback(
    ({ actionType, dataSource }) => {
      setState({
        actionType,
        optCol: dataSource,
        actionVisible: true,
      });
    },
    [setState],
  );
  const handleCancel = useCallback(() => {
    setState({ actionVisible: false });
  }, [setState]);

  const handleOk = useCallback(
    (values) => {
      const { actionType } = state;
      if (actionType === 'preview') {
        handleCancel();
      } else if (actionType === 'add') {
        setState({ loading: true });
        scheduleDispatchers.postCreate(values).then(() => {
          reset();
          handleCancel();
          setState({ loading: false });
        });
      } else if (actionType === 'edit') {
        setState({ loading: true });
        scheduleDispatchers.postUpdate(values).then(() => {
          reset();
          handleCancel();
          setState({ loading: false });
        });
      }
    },
    [handleCancel, reset, scheduleDispatchers, setState, state],
  );

  const handleDelete = useCallback(
    (data) => {
      if (!data) {
        return;
      }
      Dialog.confirm({
        title: '删除提醒',
        content: `确定删除 ${data.beanName} 吗？`,
        onOk: () => {
          scheduleDispatchers.postDelete([data.jobId]).then(() => {
            reset();
          });
        },
      });
    },
    [reset, scheduleDispatchers],
  );
  const handleDeletes = useCallback(() => {
    if (state.selected.length > 0) {
      setState({ multipleBatchBtnDis: true });
      Dialog.confirm({
        title: '删除提醒',
        content: '确定要批量删除吗？',
        onOk: () => {
          scheduleDispatchers.postDelete(state.selected).then(() => {
            reset();
          });
        },
      });
    }
  }, [reset, setState, state.selected, scheduleDispatchers]);
  const handlePause = useCallback(
    (data) => {
      if (!data) {
        return;
      }
      Dialog.confirm({
        title: '提示',
        content: `确定暂停 ${data.beanName} 吗？`,
        onOk: () => {
          scheduleDispatchers.postPause([data.jobId]).then(() => {
            reset();
          });
        },
      });
    },
    [reset, scheduleDispatchers],
  );
  const handlePauses = useCallback(() => {
    if (state.selected.length > 0) {
      setState({ multipleBatchBtnDis: true });
      Dialog.confirm({
        title: '提示',
        content: '确定要批量暂停吗？',
        onOk: () => {
          scheduleDispatchers.postPause(state.selected).then(() => {
            reset();
          });
        },
      });
    }
  }, [reset, scheduleDispatchers, setState, state.selected]);

  const handleResume = useCallback(
    (data) => {
      if (!data) {
        return;
      }
      Dialog.confirm({
        title: '提示',
        content: '确定要恢复吗？',
        onOk: () => {
          scheduleDispatchers.postResume([data.jobId]).then(() => {
            reset();
          });
        },
      });
    },
    [reset, scheduleDispatchers],
  );

  const handleResumes = useCallback(() => {
    if (state.selected.length > 0) {
      setState({ multipleBatchBtnDis: true });
      Dialog.confirm({
        title: '提示',
        content: '确定要批量恢复吗？',
        onOk: () => {
          scheduleDispatchers.postResume(state.selected).then(() => {
            reset();
          });
        },
      });
    }
  }, [reset, scheduleDispatchers, setState, state.selected]);

  const handleRun = useCallback(
    (data) => {
      if (!data) {
        return;
      }
      Dialog.confirm({
        title: '提示',
        content: '确定要立即执行吗？',
        onOk: () => {
          scheduleDispatchers.postRun([data.jobId]).then(() => {
            reset();
          });
        },
      });
    },
    [reset, scheduleDispatchers],
  );

  const handleRuns = useCallback(() => {
    if (state.selected.length > 0) {
      setState({ multipleBatchBtnDis: true });
      Dialog.confirm({
        title: '提示',
        content: '确定要批量立即执行吗？',
        onOk: () => {
          scheduleDispatchers.postRun(state.selected).then(() => {
            reset();
          });
        },
      });
    }
  }, [reset, scheduleDispatchers, setState, state.selected]);

  const stateCell = (value) => {
    let cell;
    switch (value) {
      case 0:
        cell = (
          <Tag type="normal" color="green" size="small">
            正常
          </Tag>
        );
        break;
      default:
        cell = (
          <Tag type="normal" color="red" size="small">
            暂停
          </Tag>
        );
        break;
    }
    return cell;
  };

  const cellOperation = (...args) => {
    const record = args[2];
    return (
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <Button text type="primary" onClick={() => operationCallback({ actionType: 'edit', dataSource: record })}>
          修改
        </Button>
        <Button text type="primary" onClick={() => handleDelete(record)}>
          删除
        </Button>
        <Button text type="primary" onClick={() => handlePause(record)}>
          暂停
        </Button>
        <Button text type="primary" onClick={() => handleResume(record)}>
          恢复
        </Button>
        <Button text type="primary" onClick={() => handleRun(record)}>
          立即执行
        </Button>
        <Button text type="primary" onClick={() => operationCallback({ actionType: 'preview', dataSource: record })}>
          查看
        </Button>
      </div>
    );
  };

  const handleLogListCancel = () => {
    setState({ logVisible: false });
  };

  return (
    <>
      <Head>
        <title>定时任务</title>
      </Head>
      <ResponsiveGrid gap={20}>
        <ResponsiveGrid.Cell colSpan={12}>
          <PageHeader breadcrumbs={[{ name: '系统管理' }, { name: '定时任务' }]} />
        </ResponsiveGrid.Cell>
        <ResponsiveGrid.Cell colSpan={12}>
          <Card free className={styles.container} id="table-container">
            <Card.Content>
              <div className={styles.actionBar}>
                <div className={styles.search}>
                  <Input placeholder="bean名称" />
                  <div className={styles.buttonGroup}>
                    <Button type="normal">查询</Button>
                    <Button type="primary" onClick={() => operationCallback({ actionType: 'add', dataSource: {} })}>
                      新增
                    </Button>
                    <Button type="primary" warning disabled={state.multipleBatchBtnDis} onClick={handleDeletes}>
                      批量删除
                    </Button>
                    <Button type="primary" warning disabled={state.multipleBatchBtnDis} onClick={handlePauses}>
                      批量暂停
                    </Button>
                    <Button type="primary" warning disabled={state.multipleBatchBtnDis} onClick={handleResumes}>
                      批量恢复
                    </Button>
                    <Button type="primary" warning disabled={state.multipleBatchBtnDis} onClick={handleRuns}>
                      批量立即执行
                    </Button>
                    <Button type="primary" onClick={() => setState({ logVisible: true })}>
                      日志列表
                    </Button>
                  </div>
                </div>
                <div className={styles.rightButtonGroup}>
                  <Button text onClick={() => setState({ size: state.size === 'medium' ? 'small' : 'medium' })}>
                    <TableActionIcon type="narrow" size="small" />
                  </Button>
                  <Button text onClick={() => setState({ isZebra: !state.isZebra })}>
                    <TableActionIcon type="zebra" size="small" />
                  </Button>
                </div>
              </div>
              <Table
                {...tableProps}
                primaryKey="jobId"
                rowSelection={{
                  onChange: (selectedRowKeys) => {
                    if (selectedRowKeys.length > 0) {
                      setState({ multipleBatchBtnDis: false, selected: selectedRowKeys });
                    } else {
                      setState({ multipleBatchBtnDis: true, selected: [] });
                    }
                  },
                }}
                size={state.size}
                isZebra={state.isZebra}
              >
                <Table.Column title="ID" dataIndex="jobId" width={80} sortable />
                <Table.Column title="bean名称" dataIndex="beanName" sortable />
                <Table.Column title="参数" dataIndex="params" />
                <Table.Column title="cron表达式" dataIndex="cronExpression" />
                <Table.Column title="备注" dataIndex="remark" />
                <Table.Column title="状态" dataIndex="status" width={100} align="center" cell={stateCell} sortable />
                <Table.Column title="操作" dataIndex="userId" width={256} align="center" cell={cellOperation} />
              </Table>
              <Pagination style={{ marginTop: '1rem' }} {...paginationProps} />
            </Card.Content>
          </Card>
        </ResponsiveGrid.Cell>
      </ResponsiveGrid>
      <DialogOperation
        visible={actionVisible}
        actionType={state.actionType}
        dataSource={optCol}
        onOk={handleOk}
        onClose={handleCancel}
        onCancel={handleCancel}
        loading={state.loading}
      />
      <LogList visible={state.logVisible} onClose={handleLogListCancel} />
    </>
  );
};

export default Schedule;
